<template>
  <div>
    <div>
      <a-form style="margin-top: 10px;margin-left: 5px;" :layout="'inline'">
        <a-form-item>
          <div class="main_activity_name">
            <div class="main_activity_name_content">活动名称：{{ activityName }}</div>
          </div>
        </a-form-item>
        <a-form-item class="main_operation">
          <a-button @click="handleAdd" class="main_operation_item" type="primary">
            添加优惠券
            <template #icon>
              <PlusOutlined/>
            </template>
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <a-table :columns="columns" :data-source="voucherList" row-key="id" style="word-break: break-all;">
      <template v-slot:bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'voucherDetails'">
          <a-button @click="viewVoucherDetails(record.id)" style="background-color: lightblue;">查看</a-button>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <div>
          <span>
            <a-button @click="handleEdit(record.id)" class="main_operation_button" type="primary" ghost>修改</a-button>
            <a-button v-if="record.status===0" @click="handleDelete(record.id,record.status)"
                      class="main_operation_button"
                      danger>下架</a-button>
            <a-button v-else @click="handleDelete(record.id,record.status)" class="main_operation_button"
                      type="primary">上架</a-button>
          </span>
          </div>
        </template>
      </template>
    </a-table>

    <!-- 新增或修改对话框 -->
    <a-modal
        ref="modalRef"
        v-model:visible="visible"
        @ok="handleOk"
        cancelText="取消"
        okText="确认"
    >
      <a-form :label-col="{ span: 4 }">
        <a-form-item label="支付金额" v-bind="validateInfos.payAmount">
          <a-input v-model:value="voucher.payAmount" placeholder="请输入支付金额"/>
        </a-form-item>
        <a-form-item label="抵扣金额，单位元" v-bind="validateInfos.deductionAmount">
          <a-input v-model:value="voucher.deductionAmount" placeholder="请输入抵扣金额，单位元"/>
        </a-form-item>
        <a-form-item label="优惠券类型" v-bind="validateInfos.type">
          <a-radio-group v-model:value="voucher.type">
            <a-radio :value="0">普通劵</a-radio>
            <a-radio :value="1">秒杀劵</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="状态" v-bind="validateInfos.status">
          <a-radio-group v-model:value="voucher.status">
            <a-radio :value="0">上架</a-radio>
            <a-radio :value="1">下架</a-radio>
            <a-radio :value="2">过期</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="库存" v-bind="validateInfos.stock">
          <a-input v-model:value="voucher.stock" placeholder="请输入库存"/>
        </a-form-item>
        <a-form-item label="开始时间" v-bind="validateInfos.beginTime">
          <a-space direction="vertical">
            <a-date-picker v-model:value="voucher.beginTime" valueFormat="YYYY-MM-DD HH:mm:ss"/>
          </a-space>
        </a-form-item>
        <a-form-item label="结束时间" v-bind="validateInfos.endTime">
          <a-date-picker v-model:value="voucher.endTime" valueFormat="YYYY-MM-DD HH:mm:ss"/>
        </a-form-item>
      </a-form>
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">{{ title }}</div>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {useRouter} from "vue-router";
import {addVoucher, deleteVoucher, getVoucher, getVoucherById, updateVoucher} from "@/api/activity/voucher";
import {createVNode, reactive, ref} from "vue";
import {Form, message, Modal, TableColumnType} from "ant-design-vue";
import {
  FireTwoTone,
  PlusOutlined
} from '@ant-design/icons-vue';

const router = useRouter()

//活动id
const activityId = Number(router.currentRoute.value.params.id)
//活动名称
const activityName = router.currentRoute.value.params.name

const viewVoucherDetails = (id: number) => {
  router.push(`/voucherDetails/${id}`)
}

interface DataType {
  key: string;
  id: number;
}

//标签
const columns: TableColumnType<DataType>[] = [
  {
    title: '支付金额',
    align: "center",
    width: 150,
    dataIndex: 'payAmount',
  },
  {
    title: '抵扣金额，单位元',
    align: "center",
    width: 200,
    dataIndex: 'deductionAmount',
  },
  {
    title: '优惠券类型',
    align: "center",
    width: 150,
    dataIndex: 'type',
    customRender: (text: any) => {
      return text.value === 0 ? '普通劵' : '秒杀劵';
    }
  },
  {
    title: '状态',
    align: "center",
    width: 150,
    dataIndex: 'status',
    customRender: (text: any) => {
      return text.value === 0 ? '上架' : (text.value === 1 ? '下架' : '过期');
    }
  },
  {
    title: '库存',
    align: "center",
    width: 100,
    dataIndex: 'stock',
  },
  {
    title: '开始时间',
    align: "center",
    width: 200,
    dataIndex: 'beginTime',
  },
  {
    title: '结束时间',
    align: "center",
    width: 200,
    dataIndex: 'endTime',
  },
  {
    title: '抢购详情',
    align: "center",
    width: 100,
    dataIndex: 'voucherDetails',
  },
  {
    title: '操作',
    align: "center",
    dataIndex: 'operation',
  },
]

//优惠券列表
const voucherList = ref()

//根据活动id获取优惠券
const handleVoucherById = () => {
  getVoucherById(activityId).then((res) => {
    voucherList.value = res.data.data.list
  })
}

//是否显示修改对话框
const visible = ref<boolean>(false);
//对话框标题
const title = ref("")

//优惠券信息
const voucher = ref({
  id: '',
  activityId: activityId,
  payAmount: '',
  deductionAmount: '',
  type: '',
  status: '',
  stock: '',
  beginTime: '',
  endTime: ''
})

//表单校验
const rulesRef = reactive({
  payAmount: [
    {
      required: true,
      message: '支付金额不能为空',
    }
  ],
  deductionAmount: [
    {
      required: true,
      message: '抵扣金额不能为空',
    }
  ],
  type: [
    {
      required: true,
      message: '类型(0:普通劵,1:秒杀劵)不能为空',
    }
  ],
  status: [
    {
      required: true,
      message: '状态(0:上架,1:下架,3:过期)不能为空',
    }
  ],
  stock: [
    {
      required: true,
      message: '库存不能为空',
    }
  ],
  beginTime: [
    {
      required: true,
      message: '开始时间不能为空',
    }
  ],
  endTime: [
    {
      required: true,
      message: '结束时间不能为空',
    }
  ],
});

const useForm = Form.useForm;
const {validate, validateInfos} = useForm(voucher, rulesRef);

//修改优惠券
const handleEdit = (id: number) => {
  reset()
  visible.value = true
  title.value = "修改优惠券信息"
  getVoucher(id).then((res) => {
    voucher.value = res.data.data.voucher
  })
}

//上架或下架优惠券
//删除活动
const handleDelete = (id: number, status: number) => {
  const flag = status === 0 ? '下架' : '上架'
  Modal.confirm({
    title: `你确定要${flag}活动吗?`,
    icon: createVNode(FireTwoTone),
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
        deleteVoucher(id, status === 0 ? 1 : 0).then(() => {
          message.success(`${flag}成功`)
          handleVoucherById()
        })
      }).catch(() => console.log('Oops errors!'));
    },
    onCancel() {
    },
  });
}

//新增优惠券
const handleAdd = () => {
  reset()
  title.value = "新增活动信息"
  visible.value = true
}

//新增或修改提交按钮
const handleOk = () => {
  validate().then(() => {
    if (voucher.value.id != '') {
      updateVoucher(voucher.value).then((res) => {
        if (res.data.code === 400) {
          message.warn(res.data.message)
        } else {
          visible.value = false;
          handleVoucherById()
        }
      })
    } else {
      addVoucher(voucher.value).then((res) => {
        if (res.data.code === 400) {
          message.warn(res.data.message)
        } else {
          visible.value = false;
          handleVoucherById()
        }
      })
    }
  }).catch(err => {
    console.log('error', err);
  });
}

//对话框表单重置
const reset = () => {
  voucher.value.payAmount = ''
  voucher.value.deductionAmount = ''
  voucher.value.type = ''
  voucher.value.status = ''
  voucher.value.stock = ''
  voucher.value.beginTime = ''
  voucher.value.endTime = ''
}

handleVoucherById()
</script>

<style lang="less" scoped>
.main_activity_name {
  margin-top: 10px;
  height: 34px;
  background-color: paleturquoise;
  line-height: 24px;

  .main_activity_name_content {
    font-size: 15px;
    padding: 5px;
  }
}

.main_operation {
  margin: 10px;
  display: flex;

  .main_operation_item {
    margin-right: 10px;
  }

  .main_operation_edit {
    background-color: palegreen;
    margin-right: 10px;
  }

  .main_operation_export {
    background-color: sandybrown;
    margin-right: 10px;
  }
}

.main_rest {
  margin-left: 5px;
}

.main_operation_button {
  margin: 5px;
}

:deep(.ant-form-item-control-input-content) {
  margin-bottom: 5px;
}
</style>